// AI 集成测试页面

import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { FiPlay, FiLoader, FiCheckCircle, FiXCircle } from 'react-icons/fi';
import { aiService } from '../services/aiService';
import { AI_CONFIG } from '../config/aiConfig';

const AITest: React.FC = () => {
  const [isGenerating, setIsGenerating] = useState(false);
  const [isDefining, setIsDefining] = useState(false);
  const [healthStatus, setHealthStatus] = useState<'unknown' | 'checking' | 'healthy' | 'unhealthy'>('unknown');
  const [sceneResult, setSceneResult] = useState<any>(null);
  const [definitionResult, setDefinitionResult] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);

  const testWords = ['cat', 'house', 'book', 'happy', 'run'];

  const testHealthCheck = async () => {
    setHealthStatus('checking');
    setError(null);
    
    try {
      const isHealthy = await aiService.healthCheck();
      setHealthStatus(isHealthy ? 'healthy' : 'unhealthy');
      if (!isHealthy) {
        setError('AI 服务健康检查失败');
      }
    } catch (err) {
      setHealthStatus('unhealthy');
      setError(err instanceof Error ? err.message : 'Unknown error');
    }
  };

  const testSceneGeneration = async () => {
    setIsGenerating(true);
    setError(null);
    
    try {
      const result = await aiService.generateScene({
        words: testWords.slice(0, 3),
        language: 'zh',
        difficulty: 'intermediate',
        sceneType: 'daily'
      });
      setSceneResult(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Scene generation failed');
    } finally {
      setIsGenerating(false);
    }
  };

  const testWordDefinition = async () => {
    setIsDefining(true);
    setError(null);
    
    try {
      const result = await aiService.getWordDefinition('beautiful', 'zh');
      setDefinitionResult(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Word definition failed');
    } finally {
      setIsDefining(false);
    }
  };

  const getHealthIcon = () => {
    switch (healthStatus) {
      case 'checking': return <FiLoader className="w-5 h-5 animate-spin" />;
      case 'healthy': return <FiCheckCircle className="w-5 h-5 text-green-500" />;
      case 'unhealthy': return <FiXCircle className="w-5 h-5 text-red-500" />;
      default: return <FiPlay className="w-5 h-5" />;
    }
  };

  return (
    <div className="max-w-4xl mx-auto p-6 space-y-6">
      <div className="text-center">
        <h1 className="text-3xl font-bold text-gray-800 mb-2">AI 服务集成测试</h1>
        <p className="text-gray-600">测试您的 DeepSeek 模型集成是否正常工作</p>
      </div>

      {/* 配置信息 */}
      <motion.div
        className="bg-blue-50 rounded-lg p-4"
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
      >
        <h3 className="text-lg font-semibold text-blue-800 mb-3">当前配置</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
          <div>
            <span className="font-medium text-blue-700">服务地址:</span>
            <span className="ml-2 font-mono text-blue-600">{AI_CONFIG.DEEPSEEK.baseURL}</span>
          </div>
          <div>
            <span className="font-medium text-blue-700">模型:</span>
            <span className="ml-2 text-blue-600">{AI_CONFIG.DEEPSEEK.model}</span>
          </div>
          <div>
            <span className="font-medium text-blue-700">API Key:</span>
            <span className="ml-2 text-blue-600">{AI_CONFIG.DEEPSEEK.apiKey ? '已设置' : '未设置'}</span>
          </div>
          <div>
            <span className="font-medium text-blue-700">超时时间:</span>
            <span className="ml-2 text-blue-600">{AI_CONFIG.REQUEST.timeout}ms</span>
          </div>
        </div>
      </motion.div>

      {/* 测试按钮 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <motion.button
          onClick={testHealthCheck}
          disabled={healthStatus === 'checking'}
          className="flex items-center justify-center gap-3 bg-white border-2 border-blue-200 hover:border-blue-400 rounded-lg p-4 transition-all"
          whileHover={{ scale: 1.02 }}
          whileTap={{ scale: 0.98 }}
        >
          {getHealthIcon()}
          <span className="font-medium">健康检查</span>
        </motion.button>

        <motion.button
          onClick={testSceneGeneration}
          disabled={isGenerating}
          className="flex items-center justify-center gap-3 bg-white border-2 border-green-200 hover:border-green-400 rounded-lg p-4 transition-all"
          whileHover={{ scale: 1.02 }}
          whileTap={{ scale: 0.98 }}
        >
          {isGenerating ? <FiLoader className="w-5 h-5 animate-spin" /> : <FiPlay className="w-5 h-5" />}
          <span className="font-medium">测试场景生成</span>
        </motion.button>

        <motion.button
          onClick={testWordDefinition}
          disabled={isDefining}
          className="flex items-center justify-center gap-3 bg-white border-2 border-purple-200 hover:border-purple-400 rounded-lg p-4 transition-all"
          whileHover={{ scale: 1.02 }}
          whileTap={{ scale: 0.98 }}
        >
          {isDefining ? <FiLoader className="w-5 h-5 animate-spin" /> : <FiPlay className="w-5 h-5" />}
          <span className="font-medium">测试单词定义</span>
        </motion.button>
      </div>

      {/* 错误显示 */}
      {error && (
        <motion.div
          className="bg-red-50 border border-red-200 rounded-lg p-4"
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
        >
          <div className="flex items-center gap-2">
            <FiXCircle className="w-5 h-5 text-red-500" />
            <h4 className="font-semibold text-red-800">错误</h4>
          </div>
          <p className="text-red-700 mt-1 font-mono text-sm">{error}</p>
        </motion.div>
      )}

      {/* 场景生成结果 */}
      {sceneResult && (
        <motion.div
          className="bg-green-50 border border-green-200 rounded-lg p-4"
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
        >
          <h4 className="font-semibold text-green-800 mb-3">场景生成结果</h4>
          <div className="space-y-2 text-sm">
            <div>
              <span className="font-medium text-green-700">标题:</span>
              <span className="ml-2 text-green-600">{sceneResult.title}</span>
            </div>
            <div>
              <span className="font-medium text-green-700">描述:</span>
              <p className="text-green-600 mt-1">{sceneResult.description}</p>
            </div>
            <div>
              <span className="font-medium text-green-700">图像提示:</span>
              <p className="text-green-600 mt-1 font-mono text-xs">{sceneResult.imagePrompt}</p>
            </div>
            <div>
              <span className="font-medium text-green-700">单词上下文 ({sceneResult.wordContexts?.length || 0}):</span>
              <ul className="text-green-600 mt-1 space-y-1">
                {sceneResult.wordContexts?.map((wc: any, idx: number) => (
                  <li key={idx} className="text-xs">
                    • {wc.word}: {wc.contextDescription} (位置: {wc.position?.x}%, {wc.position?.y}%)
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </motion.div>
      )}

      {/* 单词定义结果 */}
      {definitionResult && (
        <motion.div
          className="bg-purple-50 border border-purple-200 rounded-lg p-4"
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
        >
          <h4 className="font-semibold text-purple-800 mb-3">单词定义结果</h4>
          <div className="space-y-2 text-sm">
            <div>
              <span className="font-medium text-purple-700">定义:</span>
              <span className="ml-2 text-purple-600">{definitionResult.definition}</span>
            </div>
            <div>
              <span className="font-medium text-purple-700">音标:</span>
              <span className="ml-2 text-purple-600 font-mono">{definitionResult.pronunciation}</span>
            </div>
            <div>
              <span className="font-medium text-purple-700">词性:</span>
              <span className="ml-2 text-purple-600">{definitionResult.partOfSpeech}</span>
            </div>
            <div>
              <span className="font-medium text-purple-700">例句:</span>
              <ul className="text-purple-600 mt-1 space-y-1">
                {definitionResult.examples?.map((example: string, idx: number) => (
                  <li key={idx} className="text-xs">• {example}</li>
                ))}
              </ul>
            </div>
          </div>
        </motion.div>
      )}
    </div>
  );
};

export default AITest;
